<!--
 * @Descripttion: 
 * @version: 
 * @Author: ybac
 * @Date: 2022-10-31 17:46:47
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-06-25 16:50:42
-->
<template>
  <div class="home-wrap">
    <div>
      <a-card :bordered="false" class="jek-card" style="height: calc(100vh - 174px)">
        <a-button @click="handleShowFilter" icon="filter"
          >筛选 <span class="filter-num" style="margin-left: 5px">{{ ' ' + filteredNums }}</span></a-button
        >
        <a-button @click="showColumn" icon="unordered-list" class="btns">设置列</a-button>
        <div class="right-btn">
          <a-button type="primary" @click="onClickAdd">+新建</a-button>
        </div>
        <a-table
          row-key="id"
          :key="tableKey"
          size="small"
          :scroll="{ x: '500px', y: 'calc(100vh - 300px)' }"
          :hideDefaultSelections="false"
          :columns="columns"
          :dataSource="tableData"
          :pagination="false"
          @change="tableChange"
          :components="drag(columns, 'ROLE_MANAGEMENT')"
          class="jek-table"
          :loading="loadingTable"
        >
          <div slot="actions" slot-scope="text, record">
            <a type="link" @click="onClickSetUser(record)">用户</a>
            <!-- <a-button type="link" @click="onClickSetUser(record)">用户</a-button> -->
            <a-dropdown v-show="record.internalRoleFlag != '1'" style="margin-left: 20px">
              <a class="ant-dropdown-link" @click="(e) => e.preventDefault()">更多</a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a-button type="link" @click="authorize(record)">授权</a-button>
                </a-menu-item>
                <a-menu-item>
                  <a-button type="link" @click="onClickEdit(record)">编辑</a-button>
                </a-menu-item>
                <a-menu-item>
                  <a-popconfirm placement="top" ok-text="确认" cancel-text="取消" @confirm="onClickDelete(record.id)">
                    <template slot="title">
                      <span>确定删除吗？</span>
                    </template>
                    <a-button type="link" style="color: #f25643">删除</a-button>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </div>
          <!-- 输入框搜索 -->
          <div slot="searchInput" slot-scope="{ column }" class="searchWorkOreder">
            <a-input
              placeholder="请输入"
              v-model="filterForm[column.searchKey]"
              style="width: 188px; display: block"
              @pressEnter="handleFilter(filterForm)"
            />
            <a-button
              type="primary"
              style="width: 80px; margin-left: 20px; display: block"
              @click="handleFilter(filterForm)"
            >
              搜索
            </a-button>
          </div>
          <a-icon
            slot="searchIcon"
            slot-scope="filtered"
            type="search"
            :style="{ color: filtered ? '#108ee9' : undefined }"
          />
        </a-table>
        <SetColumn
          columnName="设置列"
          ref="SetColumn"
          v-if="showSetColumn"
          @sureBtn="sureBtn"
          @cancelBtn="showSetColumn = false"
        />
      </a-card>
    </div>
    <search-modal ref="searchModal" @handleFilter="handleFilter" :roleList="roleList"></search-modal>
    <div class="uni-card pagination-contian" :style="{ left: collapsed ? '219px' : '90px' }">
      <div class="check-contain">
        <span style="margin-left: 8px">
          {{ `共 ${pagination.total} 条` }}
        </span>
      </div>
      <div class="page-contain">
        <a-pagination
          :total="pagination.total"
          v-model="pagination.current"
          :page-size-options="pagination.options"
          :page-size="pagination.pageSize"
          @change="onChangePage"
          @showSizeChange="onChangePage"
          show-quick-jumper
          show-size-changer
        />
      </div>
    </div>
    <form-page ref="formPage" :tenantData="tenantData" @success="requestData"></form-page>
    <user-table ref="userTable" @success="requestData"></user-table>
    <authorization ref="authorization" />
  </div>
</template>

<script>
import { getNewColumns } from '@/utils/util'
import SetColumn from '@/pubComponent/SetColumn.vue'
import tableDragResize from '@/mixins/tableDragResize'
import formPage from './form.vue'
import authorization from './modal/authorization.vue'
import moment from 'moment'
import searchModal from './searchModal.vue'
import { columnsValue } from './column'
import { mapState } from 'vuex'
import { getAction, deleteAction } from '@/api/manage'
import userTable from './modal/user/index.vue'
const actionArr = [
  {
    fixed: 'right',
    title: '操作',
    width: 150,
    dataIndex: 'actions',
    ellipsis: true,
    scopedSlots: { customRender: 'actions' },
  },
]
export default {
  name: 'roleManagement',
  mixins: [tableDragResize],
  components: {
    SetColumn,
    formPage,
    searchModal,
    authorization,
    userTable,
  },
  data() {
    return {
      moment,
      url: {
        exportXlsUrl: '/sys/user/exportsysUserXls',
      },
      tableKey: 1.9,
      columnsValue,
      columns: JSON.parse(JSON.stringify(columnsValue)),
      tableData: [],
      departmentTree: [],
      pagination: {
        current: 1,
        pageSize: 10,
        options: ['10', '20', '30', '40', '50'],
        total: 0,
      },
      filterForm: {},
      sortForm: {},
      showSetColumn: false,
      selectedRowKeys: [],
      selectedRows: [],
      listCheckAll: false,
      listIndeterminate: false,
      loadingRowKey: null,
      departVisible: false,
      roleVisible: false,
      singgleRoleVisible: false,
      confirmLoading: false,
      modalForm: this.$form.createForm(this, { name: 'coordinated' }),
      loadingTable: false,
      tenantData: [],
      tenantId: '',
      departId: '',
      dataByTenant: true,
      roleList: [],
      boxGroup: [],
      userRecord: [],
      oldRoleSids: [],
    }
  },
  created() {
    this.tenantId = this.$store.getters.tenantid
    var oldValue = localStorage.getItem(this.BUSI_CONST.Entity.ROLE_MANAGEMENT)
    this.columns = getNewColumns(this.columnsValue, JSON.parse(oldValue), actionArr, this.columns)
    this.requestData()
  },
  computed: {
    ...mapState({
      collapsed: (state) => state.user.collapsedAno,
    }),
    filteredNums() {
      let nums = 0
      for (let key in this.filterForm) {
        if (this.filterForm[key]) {
          nums += 1
        }
      }
      return nums
    },
    scrollX() {
      let xnum = 0
      for (let item of this.columns) {
        xnum += Number(item.width) || 0
      }
      return xnum
    },
  },
  methods: {
    // 授权
    authorize(obj) {
      this.$refs.authorization.open(obj)
    },
    // 增
    onClickAdd() {
      this.$refs.formPage.open()
    },
    // 删
    onClickDelete(id) {
      if (id) {
        //单个删除
        deleteAction('/sys/role/delete', { id, tenantId: this.tenantId }).then((res) => {
          if (res.code == 200) {
            this.$antdMessage.success('删除成功！')
            if (this.tableData.length === 1) {
              this.pagination.current = this.pagination.current == 1 ? 1 : this.pagination.current - 1
            }
            this.requestData()
          } else {
            this.$antdMessage.error(res.message)
          }
        })
      } else {
      }
    },
    onClickSetUser(record) {
      this.$refs.userTable.open(record)
    },
    // 改
    onClickEdit(record) {
      this.$refs.formPage.editor(record)
    },
    // 查
    requestData() {
      this.loadingTable = true
      let params = {
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
        tenantId: this.tenantId,
        ...this.filterForm,
        ...this.sortForm,
      }

      getAction('/sys/role/list', params)
        .then((res) => {
          if (res.code == 200) {
            this.tableData = res.result.records || []
            this.pagination.total = res.result.total
          } else {
            this.$antdMessage.error(res.message)
          }
          this.loadingTable = false
        })
        .catch((err) => {
          this.loadingTable = false
          console.log(err)
        })
    },
    // 排序
    tableChange(pagination, filters, sorter, { currentDataSource }) {
      this.current = 1
      if (sorter.order) {
        let sortType = ''
        if (sorter.order == 'ascend') {
          sortType = 'ASC'
        } else {
          sortType = 'DESC'
        }
        this.sortForm = {
          sortType: sortType,
          sortColumn: sorter.columnKey,
        }
        this.requestData()
      } else {
        this.sortForm = {
          sortType: '',
          sortColumn: '',
        }
        this.requestData()
      }
    },
    // 筛选
    handleShowFilter() {
      this.$refs.searchModal.openFilter(this.filterForm)
    },
    handleFilter(form) {
      console.log('form是怎样：', form)
      this.pagination.current = 1
      this.filterForm = JSON.parse(JSON.stringify(form))
      this.requestData()
    },
    // 分页
    onChangePage(current, pageSize) {
      this.pagination.current = current
      this.pagination.pageSize = pageSize
      this.requestData()
    },
    /* 打开设置列面板 */
    showColumn() {
      this.showSetColumn = true
      this.$nextTick(() => {
        this.$refs.SetColumn.paramsData(this.columnsValue, this.BUSI_CONST.Entity.ROLE_MANAGEMENT, this.columns)
      })
    },
    /* 设置列 */
    sureBtn(emitArr) {
      localStorage.setItem(this.BUSI_CONST.Entity.ROLE_MANAGEMENT, JSON.stringify(emitArr))
      this.columns = getNewColumns(this.columnsValue, emitArr, actionArr)
      this.tableKey += 1
    },
  },
}
</script>

<style lang="less" scoped>
@import '~@/assets/less/public.less';
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
.flex-box {
  display: flex;
}
.searchWorkOreder {
  .flex(flex-start, center);
  padding: 8px;
}
.btns {
  margin-left: 10px;
}
.right-btn {
  float: right;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
}
</style>
